package legumes.client.ui.otherboxes;

import legumes.client.evt.main.PlaceDeliverySelectionOverviewEvent;
import legumes.client.evt.main.PlaceDeliverySelectionOverviewEventHandler;
import legumes.client.evt.main.UserConnectedEvent;
import legumes.client.evt.main.UserConnectedEventHandler;
import legumes.client.evt.main.UserDisconnectedEvent;
import legumes.client.evt.main.UserDisconnectedEventHandler;
import legumes.client.evt.manager.EventBusManager;
import legumes.client.evt.store.PlaceDeliverySelectionChangedEvent;
import legumes.client.evt.store.PlaceDeliverySelectionChangedEventHandler;
import legumes.client.resources.PNResources;
import legumes.client.ui.util.wrapper.LatLngWrapper;
import legumes.client.ui.widgets.window.PaiementModesDetailsWindow;
import legumes.shared.domain.CustomerDTO;
import legumes.shared.domain.HomePlaceDelivery;
import legumes.shared.domain.PlaceDelivery;
import legumes.shared.domain.Store;

import com.google.gwt.maps.client.geocode.Geocoder;
import com.google.gwt.maps.client.geocode.LatLngCallback;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.ui.FlexTable;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.WidgetCanvas;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.LinkItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.layout.VLayout;

public class StoreInfosBoxPanel extends Window {

	private FlexTable selectedStoreFT;
	private CustomerDTO connectedUser;
	
	public StoreInfosBoxPanel() {
		super();
		setWidth100();
		setHeight(250);
		setMargin(5);
		
		setTitle("<img src=\"" + PNResources.INSTANCE.storeIcon().getURL() + "\" />&nbsp;Aucun magasin sélectionné");
		
		setShowCloseButton(false);
        setShowMinimizeButton(true);
		setCanDrag(false);
		setCanDragReposition(false);
		
		selectedStoreFT= new FlexTable();
		selectedStoreFT.setWidth("100%");
		selectedStoreFT.setHeight("100%");
        bind();
        setVisible(false);
		addItem( new WidgetCanvas(selectedStoreFT));
	}
	
	private void bind(){
		EventBusManager.getInstance().getEventBus().addHandler(
				PlaceDeliverySelectionChangedEvent.TYPE, 
				new PlaceDeliverySelectionChangedEventHandler(){

					@Override
					public void onStoreSelectionChanged(
							PlaceDeliverySelectionChangedEvent event) {
						StoreInfosBoxPanel.this.onStoreSelectionChanged( 
								event.getStore(),
								event.getPlaceDelivery() );
					}
				});
		
		EventBusManager.getInstance().getEventBus().addHandler(
				PlaceDeliverySelectionOverviewEvent.TYPE, 
				new PlaceDeliverySelectionOverviewEventHandler(){

					@Override
					public void onStoreSelectionChanged(
							PlaceDeliverySelectionOverviewEvent event) {
						StoreInfosBoxPanel.this.onStoreSelectionChanged( 
								event.getStore(),
								event.getPlaceDelivery() );
					}
				});
		
		EventBusManager.getInstance().getEventBus().addHandler(
				UserConnectedEvent.TYPE, 
				new UserConnectedEventHandler(){

					@Override
					public void onUserConnected(UserConnectedEvent event) {
						connectedUser = event.getCustomerDTO();
					}
				});
		
		EventBusManager.getInstance().getEventBus().addHandler(
				UserDisconnectedEvent.TYPE, 
				new UserDisconnectedEventHandler(){
					@Override
					public void onUserDisconnected(UserDisconnectedEvent event) {
						connectedUser = null;
					}
				});
	}
	
	private void onStoreSelectionChanged(Store st_, PlaceDelivery pd_){
		if (st_ != null){
			StoreInfosBoxPanel.this.setVisible(true);
		} else {
			StoreInfosBoxPanel.this.setVisible(false);
		}
		refreshData(st_, pd_);
	}
	
	private void refreshData(Store st_, PlaceDelivery pd_){
		String iconURL;
		String deliveringAdress;
		selectedStoreFT.setHTML(0, 0, "<i>Prochaine livraison:</i> ");
		//TODO Retrieve the address of next delivering
		selectedStoreFT.setText(0, 1, "10/06/2007 16h");
		
		if(pd_ instanceof HomePlaceDelivery){
			HomePlaceDelivery hpd = (HomePlaceDelivery)pd_;
			iconURL = PNResources.INSTANCE.deliveringAtHomeIcon().getURL();
			deliveringAdress = "Livraison à domicile";
			if( connectedUser == null ){
				selectedStoreFT.setWidget(2, 0, buildCheckDeliverableAtHomePanel(hpd));
				selectedStoreFT.getFlexCellFormatter().setColSpan(2, 0, 2);
			} else {
				//TODO Show user addresses which are deliverable
				//connectedUser.get
			}
		}else {
			iconURL = PNResources.INSTANCE.deliveringAtMarketIcon().getURL();
			if( pd_.getPostalAdress() != null ){
				deliveringAdress = pd_.getPostalAdress().toStringHTMLAdressPostal();
			} else {
				deliveringAdress = "Adresse NC";
			}
			selectedStoreFT.setText(2, 0, "");
			selectedStoreFT.getFlexCellFormatter().setColSpan(1, 0, 2);
		}
		setTitle("<img src=\"" + iconURL + "\" />&nbsp;" +
				st_.getStoreName() );
		selectedStoreFT.setHTML(1, 0, deliveringAdress);
		
		selectedStoreFT.setWidget(3, 0, buildPaiementModes(st_));
		selectedStoreFT.getFlexCellFormatter().setColSpan(3, 0, 2);
	}
	
	private VLayout buildPaiementModes(final Store st_){
		StaticTextItem sti = new StaticTextItem("paiementALaLivraison", "Paiement à la livraison");
		
		LinkItem li = new LinkItem("paiementModes");
		li.setShowTitle(false);
		li.setLinkTitle("Paiement à la livraison [En savoir plus]");
		li.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				new PaiementModesDetailsWindow(st_);
			}
		});
		
		DynamicForm df = new DynamicForm();
		df.setNumCols(4);
		df.setWidth("290px");
		df.setItems(sti, li);
		
		VLayout messageFormLayout = new VLayout();
		messageFormLayout.setMembers(df, 
				new WidgetCanvas( 
						PNResources.PaiementModeImageResource.
							getAllPaiementModeImageResourceAsWidget(st_.getPaiementModes(), true)
						));
		messageFormLayout.setHeight(20);
		messageFormLayout.setWidth("290px");
		return messageFormLayout;
	}
	
	
	private VLayout buildCheckDeliverableAtHomePanel(final HomePlaceDelivery hpd_){
		Canvas txtCanvas = new Canvas();
		txtCanvas.setWidth(290);
		txtCanvas.setHeight(20);
		txtCanvas.setContents("Vérifier si ce commerçant peut vous livrer chez vous ?");
		
		final TextItem tiAdress = new TextItem("Adress", "Adresse");
		tiAdress.setWidth(200);
		tiAdress.setShowTitle(false);
		tiAdress.setValue("Tapez votre adresse ici...");
		ButtonItem bi = new ButtonItem("CheckAdress", "Vérifier");
		bi.setStartRow(false);
		bi.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(tiAdress.getValueAsString() != null && tiAdress.getValueAsString().length()>0){
					Geocoder gc = new Geocoder();
					gc.getLatLng(tiAdress.getValueAsString(), new LatLngCallback() {
						
						@Override
						public void onSuccess(LatLng point) {
							if( hpd_.canDeliverPointAdress(LatLngWrapper.converLatLng(point) ) ){
								selectedStoreFT.setHTML(1, 1, "<span title=\"OUI, vous pouvez être livré à domicile par ce commerçant.\" style=\"color:green;\"/>OUI</span>");
							} else {
								selectedStoreFT.setHTML(1, 1, "<span title=\"NON, vous ne pouvez pas être livré à domicile par ce commerçant.\" style=\"color:red;\"/>NON</span>");
							}
						}
						
						@Override
						public void onFailure() {
							selectedStoreFT.setHTML(1, 1, "<span title=\"NON, vous ne pouvez pas être livré à domicile par ce commerçant.\" style=\"color:red;\"/>Adresse incorrecte</span>");
						}
					});
				}
				
			}
		});
		DynamicForm df = new DynamicForm();
		df.setWidth("290px");
		df.setItems(tiAdress, bi);
		
		VLayout messageFormLayout = new VLayout();
		messageFormLayout.setMembers(txtCanvas, df);
		messageFormLayout.setHeight(20);
		messageFormLayout.setWidth("290px");
		return messageFormLayout;
	}
}
